package model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

/**
 * This class generates a matrix of characters of a given dimension. Characters are 
 * randomly selected from the English alphabet but it is possible to set 
 * the number of vocals. Once the class has been created it is no longer possible
 * to set dimensions or the vocal amount but the matrix may be reinitialized 
 * whenever necessary.  
 * @author lele
 * 
 *
 */
public class RandomCharMatrixCreator {

	private char[][] matrix;
	private int rows;
	private int colums;
	private int vocals;
	private static final char[] VOCALS = { 'a', 'e', 'i', 'o', 'u' };
	
	/**
	 * Creates a new matrix of random character with dimensions (rows, columns)
	 * ensuring that the number of vocals is equal or greater the specified one.	
	 * @param rows: the number of rows of the matrix.
	 * @param colums: the number of columns of the matrix.
	 * @param vocals: the minimum number of vocals in the matrix.
	 */
	public RandomCharMatrixCreator(int rows, int colums, int vocals) {
		super();
		this.rows = rows;
		this.colums = colums;
		this.vocals = vocals;
	}
	
	/**
	 * Generates or reinitializes the random matrix. Characters are randomly
	 * selected from the English alphabet.
	 * @return the newly generated matrix
	 */
	public char[][] generateMatrix() {
		
		this.matrix = new char[rows][colums];
		ArrayList<Character> list = fillList();
		Collections.shuffle(list);
		list2matrix(list);
		return matrix;
		
	}

	private ArrayList<Character> fillList() {
		ArrayList<Character> list = new ArrayList<Character>();
		Random randomGeneratr = new Random();
		insertVocals(list, randomGeneratr);
		insertNonVocals(list, randomGeneratr);
		return list;
	}

	private void insertNonVocals(ArrayList<Character> list,
			Random randomGeneratr) {
		int nonVocals = rows*colums - vocals;
		
		for (int i = 0; i < nonVocals; i++) {
			list.add((char)(97 + randomGeneratr.nextInt(25)));
		}
	}

	private void insertVocals(ArrayList<Character> list, Random randomGeneratr) {
		for (int i = 0; i < vocals; i++) {
			list.add((char)VOCALS[(randomGeneratr.nextInt(VOCALS.length))]);
		}
	}

	private void list2matrix(ArrayList<Character> list) {
		int k = 0;
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				matrix[i][j] = list.get(k);
				k++;
			}			
		}
	}
}
